package view;

import model.Major;
import service.MajorService;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.List;
import java.util.Set;
import java.util.ArrayList;
import java.util.EmptyStackException;
import javax.swing.border.EmptyBorder;
import model.Subject;
import service.SubjectService;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.TableRowSorter;
import javax.swing.RowFilter;

public class MajorManagementPanel extends JPanel {
    private static final Font TITLE_FONT = new Font("微软雅黑", Font.BOLD, 14);
    private static final Font CONTENT_FONT = new Font("微软雅黑", Font.PLAIN, 13);
    private static final Font BUTTON_FONT = new Font("微软雅黑", Font.PLAIN, 13);
    
    private MajorService majorService;
    private JTable majorTable;
    private DefaultTableModel majorTableModel;
    private JTable courseTable;
    private DefaultTableModel courseTableModel;
    private boolean readOnly;
    private String selectedMajorCode;
    private SubjectService subjectService;
    
    public MajorManagementPanel() {
        this(false);
    }
    
    public MajorManagementPanel(boolean readOnly) {
        this.readOnly = readOnly;
        this.majorService = new MajorService();
        this.subjectService = new SubjectService();
        initComponents();
        loadData();
    }
    
    private void initComponents() {
        UIManager.put("Label.font", CONTENT_FONT);
        UIManager.put("TextField.font", CONTENT_FONT);
        UIManager.put("TextArea.font", CONTENT_FONT);
        UIManager.put("Button.font", BUTTON_FONT);
        UIManager.put("Table.font", CONTENT_FONT);
        UIManager.put("TableHeader.font", TITLE_FONT);
        
        setLayout(new BorderLayout());
        
        // 创建分割面板
        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
        splitPane.setDividerLocation(500);
        
        // 左侧专业管理面板
        JPanel majorPanel = createMajorPanel();
        splitPane.setLeftComponent(majorPanel);
        
        // 右侧课程管理面板
        JPanel coursePanel = createCoursePanel();
        splitPane.setRightComponent(coursePanel);
        
        add(splitPane, BorderLayout.CENTER);
    }
    
    private JPanel createMajorPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createTitledBorder(
            BorderFactory.createEtchedBorder(),
            "专业管理",
            TitledBorder.LEFT,
            TitledBorder.TOP,
            TITLE_FONT
        ));
        
        // 工具栏
        JToolBar toolBar = new JToolBar();
        toolBar.setFloatable(false);
        
        JButton addMajorButton = new JButton("添加专业");
        JButton editMajorButton = new JButton("编辑专业");
        JButton deleteMajorButton = new JButton("删除专业");
        JButton assignCoursesButton = new JButton("分配课程");
        
        if (!readOnly) {  // 只在非只读模式下加编辑按钮
            toolBar.add(addMajorButton);
            toolBar.add(editMajorButton);
            toolBar.add(deleteMajorButton);
            toolBar.add(assignCoursesButton);
        }
        
        panel.add(toolBar, BorderLayout.NORTH);
        
        // 专业表格
        String[] columnNames = {"专业代码", "专业名称", "描述"};
        majorTableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        
        majorTable = new JTable(majorTableModel);
        JScrollPane scrollPane = new JScrollPane(majorTable);
        panel.add(scrollPane, BorderLayout.CENTER);
        
        // 添加事件监听
        addMajorButton.addActionListener(e -> showAddMajorDialog());
        editMajorButton.addActionListener(e -> editSelectedMajor());
        deleteMajorButton.addActionListener(e -> deleteSelectedMajor());
        assignCoursesButton.addActionListener(e -> showAssignCoursesDialog());
        
        // 添加表格选择监听
        majorTable.getSelectionModel().addListSelectionListener(e -> {
            if (!e.getValueIsAdjusting()) {
                updateCourseTable();
            }
        });
        
        return panel;
    }
    
    private JPanel createCoursePanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createTitledBorder(
            BorderFactory.createEtchedBorder(),
            "课程管理",
            TitledBorder.LEFT,
            TitledBorder.TOP,
            TITLE_FONT
        ));
        
        // 工具栏
        JToolBar toolBar = new JToolBar();
        toolBar.setFloatable(false);
        
        JButton addButton = new JButton("添加课程");
        addButton.addActionListener(e -> showAddCourseDialog());
        toolBar.add(addButton);
        
        panel.add(toolBar, BorderLayout.NORTH);
        
        // 课程表格
        String[] columnNames = {"ID", "课程代码", "课程名称", "学分", "学时", "操作"};
        courseTableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return column == columnNames.length - 1;
            }
            
            @Override
            public Class<?> getColumnClass(int column) {
                if (column == 3) return Double.class;  // 学分列
                if (column == 4) return Integer.class; // 学时列
                return Object.class;
            }
        };
        
        courseTable = new JTable(courseTableModel);
        
        // 设置表格行高和表头高度
        courseTable.setRowHeight(25);
        courseTable.getTableHeader().setPreferredSize(new Dimension(0, 30));
        
        // 设置列宽
        courseTable.getColumnModel().getColumn(0).setPreferredWidth(50);  // ID
        courseTable.getColumnModel().getColumn(1).setPreferredWidth(100); // 课程代码
        courseTable.getColumnModel().getColumn(2).setPreferredWidth(200); // 课程名称
        courseTable.getColumnModel().getColumn(3).setPreferredWidth(80);  // 学分
        courseTable.getColumnModel().getColumn(4).setPreferredWidth(80);  // 学时
        courseTable.getColumnModel().getColumn(5).setPreferredWidth(100); // 操作
        
        // 设置操作列的渲染器和编辑器
        ButtonEditor buttonEditor = new ButtonEditor(e -> {
            String command = e.getActionCommand();
            int row = courseTable.getSelectedRow();
            if (row != -1) {
                if ("移除".equals(command)) {  // 修改这里，匹配表格中显示的按钮文本
                    removeCourseFromMajor(row);
                }
            }
        });
        
        courseTable.getColumnModel().getColumn(5)
            .setCellRenderer(buttonEditor.getRenderer());
        courseTable.getColumnModel().getColumn(5)
            .setCellEditor(buttonEditor);
        
        panel.add(new JScrollPane(courseTable), BorderLayout.CENTER);
        return panel;
    }
    
    private void loadData() {
        loadMajorData();
        // 初始时不显示任何课程
        courseTableModel.setRowCount(0);
    }
    
    private void loadMajorData() {
        majorTableModel.setRowCount(0);
        List<Major> majors = majorService.getAllMajors();
        for (Major major : majors) {
            Object[] rowData = {
                major.getMajorCode(),
                major.getMajorName(),
                major.getDescription()
            };
            majorTableModel.addRow(rowData);
        }
    }
    
    private void updateCourseTable() {
        int selectedRow = majorTable.getSelectedRow();
        if (selectedRow == -1) return;
        
        String majorCode = (String) majorTable.getValueAt(selectedRow, 0);
        selectedMajorCode = majorCode;  // 保存当前选中的专业代码
        updateCourseTable(majorCode);
    }
    
    private void updateCourseTable(String majorCode) {
        courseTableModel.setRowCount(0);
        if (majorCode != null) {
            List<Subject> subjects = majorService.getMajorCourses(majorCode);
            for (Subject subject : subjects) {
                Object[] rowData = {
                    subject.getId(),
                    subject.getSubjectCode(),
                    subject.getSubjectName(),
                    subject.getCredits(),
                    subject.getHours(),
                    "移除"
                };
                courseTableModel.addRow(rowData);
            }
        }
    }
    
    private void showAddMajorDialog() {
        JDialog dialog = new JDialog((Frame)SwingUtilities.getWindowAncestor(this), 
            "添加专业", true);
        dialog.setLayout(new BorderLayout());
        
        // 创建表单面板
        JPanel formPanel = new JPanel(new GridBagLayout());
        formPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;
        
        // 添加表单字段
        int row = 0;
        
        // 创建所有输入组件
        JTextField codeField = new JTextField(10);
        JTextField nameField = new JTextField(20);
        JTextArea descArea = new JTextArea(3, 20);
        descArea.setLineWrap(true);
        JScrollPane descScroll = new JScrollPane(descArea);
        
        // 设置组件大小
        Dimension fieldSize = new Dimension(200, 25);
        codeField.setPreferredSize(fieldSize);
        nameField.setPreferredSize(fieldSize);
        descArea.setPreferredSize(new Dimension(200, 100));
        
        // 添加到表单
        addFormField(formPanel, "专业代码：", codeField, gbc, row++);
        addFormField(formPanel, "专业名称：", nameField, gbc, row++);
        addFormField(formPanel, "描述：", descScroll, gbc, row++);
        
        // 创建按钮
        JPanel buttonPanel = new JPanel();
        JButton saveButton = new JButton("保存");
        JButton cancelButton = new JButton("取消");
        
        // 设置按钮大小
        Dimension buttonSize = new Dimension(80, 30);
        saveButton.setPreferredSize(buttonSize);
        cancelButton.setPreferredSize(buttonSize);
        
        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);
        
        // 添加到对话框
        dialog.add(formPanel, BorderLayout.CENTER);
        dialog.add(buttonPanel, BorderLayout.SOUTH);
        
        // 设置对话框大小
        dialog.setMinimumSize(new Dimension(400, 300));
        
        // 保存按钮事件
        saveButton.addActionListener(e -> {
            if (!validateMajorInput(nameField)) {
                return;
            }
            
            Major major = new Major();
            major.setMajorCode(codeField.getText().trim());
            major.setMajorName(nameField.getText().trim());
            major.setDescription(descArea.getText().trim());
            
            if (majorService.createMajor(major)) {
                dialog.dispose();
                loadMajorData();
                JOptionPane.showMessageDialog(this, "专业添加成功！");
            } else {
                JOptionPane.showMessageDialog(this, "专业添加失败！", 
                    "错误", JOptionPane.ERROR_MESSAGE);
            }
        });
        
        // 取消按钮事件
        cancelButton.addActionListener(e -> dialog.dispose());
        
        dialog.pack();
        dialog.setLocationRelativeTo(this);
        dialog.setVisible(true);
    }
    
    private void showAssignCoursesDialog() {
        int selectedRow = majorTable.getSelectedRow();
        if (selectedRow == -1) return;
        
        String majorCode = (String) majorTable.getValueAt(selectedRow, 0);
        Major major = majorService.getMajorByCode(majorCode);
        if (major == null) return;
        
        JDialog dialog = new JDialog((Frame)SwingUtilities.getWindowAncestor(this), 
            "分配课程", true);
        dialog.setLayout(new BorderLayout(10, 10));
        
        // 创建课程列表
        DefaultTableModel model = new DefaultTableModel(
            new String[]{"课程代码", "课程名称", "学分", "学时", "操作"}, 0
        );
        
        JTable table = new JTable(model);
        List<Subject> allSubjects = subjectService.getAllSubjects();
        List<Subject> assignedSubjects = majorService.getMajorCourses(majorCode);
        
        for (Subject subject : allSubjects) {
            boolean isAssigned = assignedSubjects.stream()
                .anyMatch(s -> s.getSubjectCode().equals(subject.getSubjectCode()));
            if (!isAssigned) {
                model.addRow(new Object[]{
                    subject.getSubjectCode(),
                    subject.getSubjectName(),
                    subject.getCredits(),
                    subject.getHours(),
                    "添加"
                });
            }
        }
        
        // 设置操作列的渲染器和编辑器
        ButtonEditor buttonEditor = new ButtonEditor(e -> {
            String command = e.getActionCommand();
            int row = table.getSelectedRow();
            if (row != -1) {
                String subjectCode = (String) model.getValueAt(row, 0);
                if (majorService.assignCourseToMajor(majorCode, subjectCode)) {
                    updateCourseTable(majorCode);
                    dialog.dispose();
                }
            }
        });
        
        table.getColumnModel().getColumn(4)
            .setCellRenderer(buttonEditor.getRenderer());
        table.getColumnModel().getColumn(4)
            .setCellEditor(buttonEditor);
        
        // 添加搜索功能
        JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        JTextField searchField = new JTextField(20);
        searchField.getDocument().addDocumentListener(new DocumentListener() {
            private void search() {
                String text = searchField.getText().toLowerCase();
                TableRowSorter<DefaultTableModel> sorter = 
                    new TableRowSorter<>(model);
                if (!text.isEmpty()) {
                    sorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
                }
                table.setRowSorter(sorter);
            }
            
            @Override
            public void insertUpdate(DocumentEvent e) { search(); }
            @Override
            public void removeUpdate(DocumentEvent e) { search(); }
            @Override
            public void changedUpdate(DocumentEvent e) { search(); }
        });
        searchPanel.add(new JLabel("搜索："));
        searchPanel.add(searchField);
        
        dialog.add(searchPanel, BorderLayout.NORTH);
        dialog.add(new JScrollPane(table), BorderLayout.CENTER);
        
        // 添加关闭按钮
        JPanel buttonPanel = new JPanel();
        JButton closeButton = new JButton("关闭");
        closeButton.addActionListener(e -> dialog.dispose());
        buttonPanel.add(closeButton);
        dialog.add(buttonPanel, BorderLayout.SOUTH);
        
        dialog.setSize(600, 400);
        dialog.setLocationRelativeTo(this);
        dialog.setVisible(true);
    }
    
    private void editSelectedMajor() {
        int selectedRow = majorTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择要编辑的专业！");
            return;
        }
        
        String majorCode = (String) majorTable.getValueAt(selectedRow, 0);
        Major major = majorService.getMajorByCode(majorCode);
        
        if (major == null) {
            JOptionPane.showMessageDialog(this, "获取专业信息失败！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        showEditMajorDialog(majorCode);
    }
    
    private void showEditMajorDialog(String majorCode) {
        Major major = majorService.getMajorByCode(majorCode);
        if (major == null) {
            JOptionPane.showMessageDialog(this, 
                "找不到专业信息！", 
                "错误", 
                JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        JDialog dialog = new JDialog((Frame) SwingUtilities.getWindowAncestor(this), 
            "编辑专业", true);
        dialog.setLayout(new BorderLayout());
        
        // 创建表单面板
        JPanel formPanel = new JPanel(new GridBagLayout());
        formPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;
        
        int row = 0;
        
        // 专业代码（只读）
        JTextField codeField = new JTextField(major.getMajorCode(), 10);
        codeField.setEditable(false);
        addFormField(formPanel, "专业代码：", codeField, gbc, row++);
        
        // 专业名称
        JTextField nameField = new JTextField(major.getMajorName(), 20);
        addFormField(formPanel, "专业名称：", nameField, gbc, row++);
        
        // 描述
        JTextArea descArea = new JTextArea(major.getDescription(), 3, 20);
        descArea.setLineWrap(true);
        JScrollPane descScroll = new JScrollPane(descArea);
        addFormField(formPanel, "描述：", descScroll, gbc, row++);
        
        // 按钮面板
        JPanel buttonPanel = new JPanel();
        JButton saveButton = new JButton("保存");
        JButton cancelButton = new JButton("取消");
        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);
        
        dialog.add(formPanel, BorderLayout.CENTER);
        dialog.add(buttonPanel, BorderLayout.SOUTH);
        
        // 保存按钮事件
        saveButton.addActionListener(e -> {
            if (!validateMajorInput(nameField)) {
                return;
            }
            
            major.setMajorName(nameField.getText().trim());
            major.setDescription(descArea.getText().trim());
            
            if (majorService.updateMajor(major)) {
                dialog.dispose();
                loadMajorData();
                JOptionPane.showMessageDialog(this, "专业更新成功！");
            } else {
                JOptionPane.showMessageDialog(this, "专业更新失败！", 
                    "错误", JOptionPane.ERROR_MESSAGE);
            }
        });
        
        cancelButton.addActionListener(e -> dialog.dispose());
        
        dialog.pack();
        dialog.setLocationRelativeTo(this);
        dialog.setVisible(true);
    }
    
    private void deleteSelectedMajor() {
        int selectedRow = majorTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择要删除的专业！");
            return;
        }
        
        String majorCode = (String) majorTable.getValueAt(selectedRow, 0);
        String majorName = (String) majorTable.getValueAt(selectedRow, 1);
        
        int choice = JOptionPane.showConfirmDialog(
            this,
            "确定要删除专业 " + majorName + "（" + majorCode + "）吗？\n" +
            "注意：删除专业将同时删除相关的课程关联！",
            "删除确认",
            JOptionPane.YES_NO_OPTION,
            JOptionPane.WARNING_MESSAGE
        );
        
        if (choice == JOptionPane.YES_OPTION) {
            if (majorService.deleteMajor(majorCode)) {
                loadMajorData();
                updateCourseTable();
                JOptionPane.showMessageDialog(this, "专业删除成功！");
            } else {
                JOptionPane.showMessageDialog(this, "专业删除失败！", 
                    "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
    
    private void showAddCourseDialog() {
        // 检查是否已选择专业
        if (selectedMajorCode == null) {
            JOptionPane.showMessageDialog(this, 
                "请先选择一个专业！", 
                "提示", 
                JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        // 获取当前选中专业的名称
        int selectedRow = majorTable.getSelectedRow();
        String majorName = (String) majorTable.getValueAt(selectedRow, 1);
        
        JDialog dialog = new JDialog((Frame)SwingUtilities.getWindowAncestor(this), 
            "添加课程到专业 - " + majorName, true);
        dialog.setLayout(new BorderLayout(10, 10));
        
        // 创建课程列表
        DefaultTableModel model = new DefaultTableModel(
            new String[]{"课程代码", "课程名称", "学分", "学时", "操作"}, 0
        );
        
        JTable table = new JTable(model);
        List<Subject> allSubjects = subjectService.getAllSubjects();
        
        for (Subject subject : allSubjects) {
            if (subject.getMajorCode() == null) {  // 只显示未分配的课程
                model.addRow(new Object[]{
                    subject.getSubjectCode(),
                    subject.getSubjectName(),
                    subject.getCredits(),
                    subject.getHours(),
                    "添加"
                });
            }
        }
        
        // 设置操作列的渲染器和编辑器
        ButtonEditor buttonEditor = new ButtonEditor(e -> {
            String command = e.getActionCommand();
            int row = table.getSelectedRow();
            if (row != -1) {
                String subjectCode = (String) model.getValueAt(row, 0);
                if (majorService.assignCourseToMajor(selectedMajorCode, subjectCode)) {
                    updateCourseTable(selectedMajorCode);
                    dialog.dispose();
                }
            }
        });
        
        table.getColumnModel().getColumn(4)
            .setCellRenderer(buttonEditor.getRenderer());
        table.getColumnModel().getColumn(4)
            .setCellEditor(buttonEditor);
        
        // 添加搜索功能
        JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        JTextField searchField = new JTextField(20);
        searchField.getDocument().addDocumentListener(new DocumentListener() {
            private void search() {
                String text = searchField.getText().toLowerCase();
                TableRowSorter<DefaultTableModel> sorter = 
                    new TableRowSorter<>(model);
                if (!text.isEmpty()) {
                    sorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
                }
                table.setRowSorter(sorter);
            }
            
            @Override
            public void insertUpdate(DocumentEvent e) { search(); }
            @Override
            public void removeUpdate(DocumentEvent e) { search(); }
            @Override
            public void changedUpdate(DocumentEvent e) { search(); }
        });
        searchPanel.add(new JLabel("搜索："));
        searchPanel.add(searchField);
        
        dialog.add(searchPanel, BorderLayout.NORTH);
        dialog.add(new JScrollPane(table), BorderLayout.CENTER);
        
        // 添加关闭按钮
        JPanel buttonPanel = new JPanel();
        JButton closeButton = new JButton("关闭");
        closeButton.addActionListener(e -> dialog.dispose());
        buttonPanel.add(closeButton);
        dialog.add(buttonPanel, BorderLayout.SOUTH);
        
        dialog.setSize(600, 400);
        dialog.setLocationRelativeTo(this);
        dialog.setVisible(true);
    }
    
    private void addFormField(JPanel panel, String label, JComponent field, 
            GridBagConstraints gbc, int row) {
        gbc.gridx = 0;
        gbc.gridy = row;
        gbc.anchor = GridBagConstraints.EAST;
        panel.add(new JLabel(label), gbc);
        
        gbc.gridx = 1;
        gbc.anchor = GridBagConstraints.WEST;
        panel.add(field, gbc);
    }
    
    private void handleCourseAction(String action, int row) {
        if ("移除".equals(action)) {  // 修改这里，匹配表格中显示的按钮文本
            removeCourseFromMajor(row);
        }
    }
    
    private boolean validateMajorInput(JTextField nameField) {
        String name = nameField.getText().trim();
        if (name.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入专业名称！", 
                "错误", JOptionPane.ERROR_MESSAGE);
            nameField.requestFocus();
            return false;
        }
        return true;
    }
    
    private void showCourseDialog(String majorCode) {
        // 检查是否已选择专业
        if (majorCode == null) {
            JOptionPane.showMessageDialog(this, 
                "请先选择一个专业！", 
                "提示", 
                JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        // 获取当前选中专业的名称
        int selectedRow = majorTable.getSelectedRow();
        String majorName = (String) majorTable.getValueAt(selectedRow, 1);
        
        JDialog dialog = new JDialog((Frame)SwingUtilities.getWindowAncestor(this), 
            "分配课程到专业 - " + majorName, true);
        dialog.setLayout(new BorderLayout(10, 10));
        
        // 创建课程列表
        DefaultTableModel model = new DefaultTableModel(
            new String[]{"课程代码", "课程名称", "学分", "学时", "操作"}, 0
        );
        
        JTable table = new JTable(model);
        List<Subject> allSubjects = subjectService.getAllSubjects();
        
        // 只显示未分配专业的课程
        for (Subject subject : allSubjects) {
            if (subject.getMajorCode() == null) {
                model.addRow(new Object[]{
                    subject.getSubjectCode(),
                    subject.getSubjectName(),
                    subject.getCredits(),
                    subject.getHours(),
                    "分配"
                });
            }
        }
        
        // 设置操作列的渲染器和编辑器
        ButtonEditor buttonEditor = new ButtonEditor(e -> {
            int row = table.getSelectedRow();
            if (row != -1) {
                String subjectCode = (String) model.getValueAt(row, 0);
                if (majorService.assignCourseToMajor(majorCode, subjectCode)) {
                    updateCourseTable(majorCode);
                    dialog.dispose();
                    JOptionPane.showMessageDialog(this, "课程分配成功！");
                } else {
                    JOptionPane.showMessageDialog(dialog, "课程分配失败！", 
                        "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        
        table.getColumnModel().getColumn(4)
            .setCellRenderer(buttonEditor.getRenderer());
        table.getColumnModel().getColumn(4)
            .setCellEditor(buttonEditor);
        
        // 添加搜索功能
        JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        JTextField searchField = new JTextField(20);
        searchField.getDocument().addDocumentListener(new DocumentListener() {
            private void search() {
                String text = searchField.getText().toLowerCase();
                TableRowSorter<DefaultTableModel> sorter = 
                    new TableRowSorter<>(model);
                if (!text.isEmpty()) {
                    sorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
                }
                table.setRowSorter(sorter);
            }
            
            @Override
            public void insertUpdate(DocumentEvent e) { search(); }
            @Override
            public void removeUpdate(DocumentEvent e) { search(); }
            @Override
            public void changedUpdate(DocumentEvent e) { search(); }
        });
        searchPanel.add(new JLabel("搜索："));
        searchPanel.add(searchField);
        
        dialog.add(searchPanel, BorderLayout.NORTH);
        dialog.add(new JScrollPane(table), BorderLayout.CENTER);
        
        // 添加关闭按钮
        JPanel buttonPanel = new JPanel();
        JButton closeButton = new JButton("关闭");
        closeButton.addActionListener(e -> dialog.dispose());
        buttonPanel.add(closeButton);
        dialog.add(buttonPanel, BorderLayout.SOUTH);
        
        dialog.setSize(600, 400);
        dialog.setLocationRelativeTo(this);
        dialog.setVisible(true);
    }
    
    private void removeCourseFromMajor(int row) {
        if (selectedMajorCode == null) {
            JOptionPane.showMessageDialog(this, "请先选择专业！");
            return;
        }
        
        String subjectCode = (String) courseTable.getValueAt(row, 1);  // 获取课程代码
        String subjectName = (String) courseTable.getValueAt(row, 2);  // 获取课程名称
        
        int confirm = JOptionPane.showConfirmDialog(this,
            "确定要将课程 '" + subjectName + "' 从当前专业中移除吗？",
            "确认移除",
            JOptionPane.YES_NO_OPTION);
        
        if (confirm == JOptionPane.YES_OPTION) {
            if (majorService.removeCourseFromMajor(selectedMajorCode, subjectCode)) {
                updateCourseTable(selectedMajorCode);
                JOptionPane.showMessageDialog(this, "课程移除成功！");
            } else {
                JOptionPane.showMessageDialog(this, "课程移除失败！", 
                    "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
} 